package org.ix.shiro.service.impl;

import org.ix.shiro.config.AuthProperties;
import org.ix.shiro.service.JwtService;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Service
public class JwtServiceImpl implements JwtService {

    final Key key;
    final AuthProperties authProperties;

    @Autowired
    public JwtServiceImpl(AuthProperties authProperties) {
        this.authProperties = authProperties;
        this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(authProperties.getTokenSecretKey()));
    }

    public String createToken(String username) {
        return createToken(username, null);
    }

    public String createToken(String username, Map<String, Object> claims) {
        long now = System.currentTimeMillis();
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(key)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(now + authProperties.getTokenExpireSecond() * 1000));
        if (claims != null && !claims.isEmpty()) {
            jwtBuilder.addClaims(claims);
        }
        return jwtBuilder.compact();
    }

    public Claims parseToken(String token) throws ExpiredJwtException {
        return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
    }
}
